import { keepPreviousData, useQueries, useQuery } from '@tanstack/react-query';
import { getDicts } from '@/api/integration/dict'
const dictToMap = (data) => {
  return data.reduce((pre, cur) => {
    pre[cur.dictValue] = cur.dictLabel;
    return pre;
  }, {});
};

const getQueryOptions = (type) => {
  return {
    queryKey: ['getDicts' + '-' + type],
    queryFn: async () => {
      const res = await getDicts(type);
      return res.data || [];
    },
    stateTime: Infinity,
  }
}

// stateTime：就决定了缓存中的数据多久会变得不新鲜（不新鲜的数据但仍存在于缓存）
// cacheTime： 决定了缓存的存储时间，cacheTime 过期后的数据会从缓存中删除
export function useDictionary(types, runQuery) {
  const queries = types.map(getQueryOptions)
  return runQuery ? queries : useQueries({
    queries,
    combine: ((results) => {
      let data = {}
      results.forEach((result, idx) => {
        data[types[idx]] = result.data
      })
      return {
        data: data,
        isFetching: results.some(result => result.isFetching)
      }
    }),
  })
}

export function useDictMap(type) {
  return useQuery({
    ...getQueryOptions(type),
    select: (data) => {
      return dictToMap(data)
    }
  })
}

export function useDictOptions(type) {
  return useQuery({
    ...getQueryOptions(type),
    select: (data) => {
      return data.map(d => {
        return { label: d.dictLabel, value: d.dictValue }
      })
    }
  })
}

